import {Injectable} from '@angular/core';
import {StringUtils} from '../utils/string-utils';

@Injectable({
    providedIn: 'root'
})
export class TpStorageService {
    static KEY_ENV = 'env:';
    static KEY_MENU = 'menu:';
    static KEY_DOC = 'doc:';
    static KEY_LAST_URL = 'lastUrl';
    static KEY_AUTH = 'auth';
    static KEY_SITE = 'site';
    static KEY_TP_DOC_TOKEN = 'tp_doc_token';
    static KEY_URL = 'url';
    static KEY_MY_FOCUS = 'my:focus';
    static UNCLEAR_KEYS = new Set<string>();

    constructor() {
        TpStorageService.UNCLEAR_KEYS.add('tp_doc_token');
        TpStorageService.UNCLEAR_KEYS.add('auth');
    }

    public delete(key: string) {
        window.localStorage.removeItem(key);
    }

    public set(key: string, value: string) {
        try {
            window.localStorage.setItem(key, value);
        } catch (e) {
            if (e.toString().indexOf('exceeded the quota') !== -1) {
                // 空间满了，需要清除
                console.log('空间已满，清除Doc缓存文件...');
                const clearCount = this.clearDocs();
                if (clearCount > 0) {
                    // 清除有文件
                    console.log('已清除Doc缓存:' + clearCount);
                    this.set(key, value);
                } else {
                    console.error('无可清除缓存！');
                }
            }
        }
    }

    public get(key: string): string {
        return window.localStorage.getItem(key);
    }

    public getObj(key: string): any {
        const value: string = this.get(key);
        if (value) {
            return JSON.parse(value);
        }
        return null;
    }

    public clearUser() {
        this.delete('tp_doc_token');
        this.delete('auth');
    }

    private clearDocs(): number {
        const deleteKeys = [];
        for (let i = 0; i < localStorage.length; i++) {
            const localStorageKey = localStorage.key(i);
            if (StringUtils.startWith(localStorageKey, TpStorageService.KEY_DOC)) {
                // 清除
                deleteKeys.push(localStorageKey);
            }
        }
        if (deleteKeys) {
            deleteKeys.forEach(deleteKey => {
                localStorage.removeItem(deleteKey);
                console.log('已清除Doc缓存:' + deleteKey);
            });
        }
        return deleteKeys.length;
    }

    clearLocalStorage() {
        const deleteKeys = [];
        for (let i = 0; i < localStorage.length; i++) {
            const localStorageKey = localStorage.key(i);
            if (!TpStorageService.UNCLEAR_KEYS.has(localStorageKey)) {
                // 清除
                deleteKeys.push(localStorageKey);
            }
        }
        if (deleteKeys) {
            deleteKeys.forEach(deleteKey => {
                localStorage.removeItem(deleteKey);
                console.log('已清除缓存:' + deleteKey);
            });
        }
        return deleteKeys.length;
    }
}
